<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4" style="margin-left: -20px;">
        <MainType :typeCode="typeCode" @getNode="getNode" :is-tree="false"></MainType>
      </el-col>
      <el-col :span="20">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="创建时间" prop="creationTime">
            <el-date-picker clearable
                            v-model="queryParams.creationTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择创建时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="产品名称" prop="productName">
            <el-input
              v-model="queryParams.productName"
              placeholder="请输入产品名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" v-tooltip="'搜索数据'">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" v-tooltip="'重置搜索条件'">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table :row-style="{ height: '30px' }" :cell-style="{ padding: '0px' }" height="450" border   v-loading="loading" :data="releaseList"  highlight-current-row>
          <el-table-column label="状态" align="center" prop="status"/>
          <el-table-column label="创建人" align="center" prop="creationName" :show-overflow-tooltip="true" width="100"/>
          <el-table-column label="创建时间" align="center" prop="creationTime" width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <template>
                <!-- 使用按钮作为可点击元素，并绑定点击事件 -->
                <el-button @click="handleSelect(scope.row,scope.$index)" type="text" style="text-align: left;">
                  {{ scope.row.productName }}
                </el-button>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="有效期" align="center" prop="effectiveTime" width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.effectiveTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="附件" align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.url != null && scope.row.url != ''" @click="handlePictureCardPreview(scope.row.uploadFile)" size="small"
                         type="text" v-tooltip="'查看附件'">附件</el-button>
              <el-button size="small" v-else type="text" v-tooltip="'无附件'">无附件</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="85px">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status === '审核' && scope.row.sendType==='groupSend' "
                size="mini"
                type="text"
                icon="el-icon-orange"
                @click="handleExamine(scope.row,scope.$index)"
                title="分类群发审核"
              ></el-button>
              <el-button
                v-if="scope.row.status === '审核' && scope.row.sendType==='oneClick'"
                size="mini"
                type="text"
                icon="el-icon-orange"
                @click="handleEnd(scope.row,scope.$index)"
                title="一键发送审核"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改产品发布对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body @close="cancel">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px" :inline="true">
            <div v-if="addSign !== 0">
              <el-descriptions title="">
                <el-descriptions-item label="序号">
                  <el-tag size="medium">{{ form.index }}</el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <el-form-item label="主分类" prop="administrativeArea" >
              <treeselect v-model="form.classificationId" :options="options" placeholder="请选择主分类" v-if="opt != 'details'"
                          :disabled="ReadOnly"  style="width: 178px"/>
              <el-input v-else v-model="form.label" placeholder="主分类" />
            </el-form-item>
            <el-form-item label="创建人" prop="creationName">
              <el-input v-model="form.creationName" placeholder="请输入创建人" disabled="true"/>
            </el-form-item>
            <el-form-item label="创建时间" prop="creationTime">
              <el-date-picker clearable
                              v-model="form.creationTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择创建时间"
                              style="width: 178px"
                              disabled="true">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" :disabled="ReadOnly"/>
            </el-form-item>
            <el-form-item label="有效期" prop="effectiveTime">
              <el-date-picker clearable
                              v-model="form.effectiveTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择有效期"
                              style="width: 178px"
                              :picker-options="{ disabledDate: dateOptions }"
                              :disabled="ReadOnly">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="审核人" prop="examineName" v-if="form.sendType==='groupSend'">
              <el-input v-model="form.examineName" placeholder="请选择审核人" @focus="selectOpen(0)" :disabled="ReadOnly"/>
            </el-form-item>
            <el-form-item label="区域" prop="region" >
              <Treeselect v-model="form.region" :options="optionsArea"   style="width: 178px"  :flat="true" :show-count="true" :normalizer="normalizer"  placeholder="请选择区域" :disabled="ReadOnly" />
            </el-form-item>
            <el-form-item label="产品内容" prop="content">
              <el-input v-model="form.content"   type="textarea" placeholder="请输入内容" style="width: 440px"  :disabled="ReadOnly" maxlength="200" show-word-limit/>
            </el-form-item>
            <el-form-item label="发送方式" prop="sendType" label-width="110px">
              <el-radio-group v-model="form.sendType" :disabled="ReadOnly" >
                <el-radio label="oneClick">一键发送</el-radio>
                <el-radio label="groupSend">分类群发</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.sendType === 'groupSend'" label="群发内容" prop="receiverName" >
              <el-input v-model="form.receiverName" type="textarea" placeholder="请输入内容" style="width: 420px"
                        @focus="handleTextAreaFocus" :disabled="ReadOnly" />
            </el-form-item>
            <el-form-item label="附件" prop="uploadFile" >
              <file-view v-if="show" :limit="1" :type="typeSelect" :businessId="form.uploadFile" :businessCode="typeCode"
                         style="width: 500px" ></file-view>
            </el-form-item>
            <el-form-item label="配图" prop="productPicture" >
              <file-view v-if="show" :limit="1" :type="typeSelect2" :businessId="form.productPicture" :businessCode="typeCode"
                         style="width: 500px"></file-view>
            </el-form-item>
            <el-form-item label="审核状态" prop="examineStatus" label-width="110px">
              <el-radio-group v-model="form.examineStatus" :disabled="examineRead">
                <el-radio label="through">审核通过</el-radio>
                <el-radio label="termination">审核不通过</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="终止原因" prop="endReason" v-if="form.examineStatus === 'termination'">
              <el-input v-model="form.endReason" type="textarea" placeholder="请输入终止原因" style="width: 440px"   maxlength="300" show-word-limit :disabled="examineRead"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer" v-if="addSign!==2" style="text-align: center;">
            <el-button type="primary" @click="submitForm" v-tooltip:append="'保存当前表单'">确 定</el-button>
            <el-button @click="cancel" v-tooltip:append="'关闭当前窗口'">关 闭</el-button>
          </div>
        </el-dialog>

        <!--        选择分类群发企业-->
        <el-dialog :title="title" :visible.sync="openUser" width="1400px" append-to-body>
          <el-scrollbar>

            <div class="content-box">
              <BusinessInfo :markAs="1" @change="close" @ok="selectEnterprise" :enterprise="1" :isTree="false" :train="true">
              </BusinessInfo>
            </div>
          </el-scrollbar>
        </el-dialog>
        <!--    附件展示对话框-->
        <el-dialog title="查看附件" :visible.sync="openFileList" width="500px" append-to-body v-if="openFileList">
          <UploadFile :upload-id="uploadId" :business-code="typeCode"></UploadFile>
        </el-dialog>
        <select-user ref="select" :type="userType" :sign="sign" @ok="selectUser" :isActOrQues=1></select-user>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listExamine, getRelease, examine, endStatus, updateRelease } from "@/api/product/release";
import { listType } from "@/api/maintype/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import MainType from "../../../components/MainType/index.vue";
import BusinessInfo from "../../enterprise/info/index.vue";
import FileView from "@/components/FileView/index";
import UploadFile from "../../upload/index.vue";
import SelectUser from "../../system/role/selectUser.vue";
import { listArea } from "@/api/area/area";

export default {
  name: "Release",
  components: {SelectUser, UploadFile, BusinessInfo, MainType,FileView,Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      typeCode: 'productRelease',
      uploadId:null,
      // 显示搜索条件
      showSearch: true,
      ReadOnly:false,
      addSign:0,
      show:false,
      openUser:false,
      // 总条数
      total: 0,
      //主分类
      options: null,
      //行政区域
      optionsArea:null,
      typeSelect:0,
      // 产品发布表格数据
      releaseList: [],
      openFileList:false,
      typeSelect2:1,
      // 弹出层标题
      title: "",
      userType: "1",
      examineRead:false,
      sign: '1',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        creationTime: null,
        productName: null,
        classificationId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        examineStatus: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        endReason: [
          { required: true, message: '请输入终止原因', trigger: 'blur', when: (data) => data.sendType === 'termination' },
        ],
      }
    };
  },
  created() {
    this.getList();
    this.listType();
    this.area();
  },
  methods: {
    /** 查询产品发布列表 */
    getList() {
      this.loading = true;
      listExamine(this.queryParams).then(response => {
        this.releaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    selectUser(userId, userName) {
      this.$set(this.form, 'examineId', userId)
      this.$set(this.form, 'examineName', userName)
    },
    // 取消按钮
    cancel() {
      this.show=false;
      this.open = false;
      this.reset();
    },
    selectOpen(type) {
      this.userType = 1;
      this.$refs.select.show();
    },
    area(){
      listArea({}).then(response => {
        this.optionsArea = response.data;
      });
    },
    normalizer(node){
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id:node.areaId,
        label:node.areaName,
        isDisabled:node.parentId=='000000'?true:false,
        children:node.list.length>0?node.list:0,
      }
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        createId: null,
        creationName: null,
        creationTime: null,
        productName: null,
        content: null,
        effectiveTime: null,
        uploadFile: null,
        receiverId: null,
        receiverName: null,
        operateTime: null,
        status: null,
        operateId: null,
        operateName: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        belongTo: null,
        classificationId: null,
        examineId: null,
        examineName: null,
        idPath: null,
        sendType: null,
        sendUnit: null,
        enterpriseId:[],
        endReason:null,
        examineStatus:null,
        region:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //获取当前用户在企业管理中的企业信息
    selectEnterprise(selection) {
      this.form.enterpriseId = selection.map(item => item.enterpriseId);
      this.form.receiverName = selection.map(item => item.enterpriseName).join(',');
      console.log(this.form)
      this.close()
    },
    handleEnd(row,index){
      this.reset();
      this.listType();
      const productId = row.productId || this.ids
      getRelease(productId).then(response => {
        this.form = response.data;
        this.sendTrain();
        this.typeSelect = 2;
        this.addSign = 4;
        this.form.index = index + 1;
        this.ReadOnly=true;
        this.examineRead=false;
        //把接收方的id转成数组
        this.form.enterpriseId = this.form.receiverId.split(',');
        this.show = true;
        this.open = true;
        this.title = "产品发布审核";
      });
    },
    //当有值的时候，默认打开对话框为分类群发，没值为一键发送
    sendTrain() {
      if (this.form.receiverName !== null) {
        this.sendType = "groupSend"
      } else {
        this.sendType = "oneClick"
      }
    },
    //报名截止日期控件
    dateOptions(time) {
      return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
    },
    /** 查看按钮操作 */
    handleSelect(row,index) {
      this.reset();
      this.listType();
      const productId = row.productId || this.ids
      getRelease(productId).then(response => {
        this.form = response.data;
        this.sendTrain();
        this.typeSelect = 2;
        this.typeSelect2=1;
        this.addSign = 2;
        this.ReadOnly=true;
        this.examineRead=true;
        this.form.index = index + 1;
        //把接收方的id转成数组
        this.form.enterpriseId = this.form.receiverId.split(',');
        this.show = true;
        this.open = true;
        this.title = "查看产品发布信息";
      });
    },
    handleExamine(row,index){
      this.reset();
      this.listType();
      const id = row.productId || this.ids
      getRelease(id).then(response => {
        this.form = response.data;
        this.sendTrain();
        this.typeSelect = 2;
        this.typeSelect2=0;
        this.addSign = 3;
        this.form.index = index + 1;
        this.ReadOnly=true;
        //把接收方的id转成数组
        this.form.enterpriseId = this.form.receiverId.split(',');
        this.show = true;
        this.open = true;
        this.title = "审核政策发布";
      });
    },
    //点击接收方文本域,弹出选择当前用户在企业管理中的企业信息
    handleTextAreaFocus() {
      this.openUser = true;
    },
    //获取树节点数据
    listType() {
      listType({ typeCode: 'productRelease' }).then(res => {
        console.log(res);
        this.options = res.data;
      })
    },
    close() {
      this.openUser = false
    },
    //树点击事件
    getNode(data, node, obj) {
      console.log(data)
      if (data.parentId != '00000000-0000-0000-0000-000000000000') {
        this.queryParams.classificationId = data.id
      } else {
        this.queryParams.classificationId = null
      }
      this.getList()
    },
    handlePictureCardPreview(id) {
      this.uploadId=id;
      this.openFileList = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.examineStatus==='through' || this.form.sendType==='groupSend') {
            examine(this.form.productId).then(res => {
              if (res.code === 200) {
                this.$message.success("审核成功");
                this.show = false;
                this.open = false;
                this.getList();
              } else {
                this.$message.error("审核失败");
                this.show = false;
                this.open = false;
                this.getList();
              }
            })
          }else {
            endStatus(this.form).then(res=>{
              if (res.code===200){
                this.$message.success("终止成功");
                this.show=false;
                this.open=false;
                this.getList();
              }else {
                this.$message.error("终止失败");
                this.show=false;
                this.open=false;
                this.getList();
              }
            })
          }
        }
      });
    },
  }
};
</script>
